<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
	<title>Upload File</title> 
	<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
	 <style type="text/css">
	body{
		margin: 1em;
	}
	</style>
</head> 
 
<body>
<?php
	$error = "";
	$msg = "";
	$img_field = 'image';
	$valid_types = array("image/gif", "image/png", "image/jpg", "image/jpeg");
	if(!empty($_FILES[$img_field]['error']))
	{
		switch($_FILES[$img_field]['error'])
		{

			case '1':
				$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
				break;
			case '2':
				$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
				break;
			case '3':
				$error = 'The uploaded file was only partially uploaded';
				break;
			case '4':
				$error = 'No file was uploaded.';
				break;

			case '6':
				$error = 'Missing a temporary folder';
				break;
			case '7':
				$error = 'Failed to write file to disk';
				break;
			case '8':
				$error = 'File upload stopped by extension';
				break;
			case '999':
			default:
				$error = 'No error code avaiable';
		}
	}elseif(empty($_FILES[$img_field]['tmp_name']) || $_FILES[$img_field]['tmp_name'] == 'none')
	{
		$error = 'No file was uploaded..';
	}else 
	{
			$tmp_name = $_FILES[$img_field]["tmp_name"];
			$name = $_FILES[$img_field]['name'];
			$type = $_FILES[$img_field]['type'];
			
			$msg .= " File Name: " . $name . ", ";
			$msg .= "<br> File Size: " . @filesize($_FILES[$img_field]['tmp_name']);
			$msg .= "<br> File Size2: " . $_FILES[$img_field]['size'];
			$msg .= "<br> File Mime: " . $type;
			$msg .= "<br> Stored at: ".$tmp_name;
			
			if (! in_array($type, $valid_types)){
				$error = "Invalid image type! (Valid types are: ";
				foreach ($valid_types as $t) {
					$error .= '<em>'.$t.'</em>, ';
				}
				')';
			}else{
				
				//todo: handle duplicate names:
				move_uploaded_file($tmp_name, '../../../assets/news/tmp/'.$name);
			}
			

	}		
	if (empty($error)){
		echo "File (<em>$name</em>) uploaded successfully!";
		// echo		"<br><b>info</b>:<br> '" . $msg . "\n";
	}else{
		echo		"error: " . $error . "\n";
		echo		"<br><b>info</b>:<br> " . $msg . "\n";
	}
	
?>
<br><br><button onclick="window.close();">Close window</button>
<?php if (empty($error)) { ?>
	
<script type="text/javascript">
img_displayer = window.opener.document.getElementById('uploaded_img_display');
img_field = window.opener.document.getElementById('uploaded_img_field');
btn = window.opener.document.getElementById('upload_img_btn');
img_displayer.innerHTML = '<?php echo $name ?>';
img_field.value = '<?php echo $name ?>';
btn.innerHTML = "Change Image";
window.close();
</script>

<?php 	} ?>
</body> 
</html>